//
//  ShoppingMainVC.m
//  代理端
//
//  Created by sliver on 15/12/14.
//  Copyright (c) 2015年 sliver. All rights reserved.
//

#import "BalanceVC.h"
#import "StockVC.h"
#import "ApplyVC.h"
#import "AboutOurVC.h"
#import "ShoppingMainVC.h"
#import "OrderMainVC.h"
#import "HeadVC.h"
#import "Unit.h"
#import "ConcludeOrderVC.h"
#import "AgentVC.h"
#import "WXDataService.h"
#import "UIImageView+WebCache.h"
#import "TypeBtn.h"
#import "ShopTableViewCell.h"
#import "AgentVC.h"
#import "objmodel.h"
@interface ShoppingMainVC ()<UITableViewDelegate,UITableViewDataSource>
{
    UIView *mainView; //主页view
    UIView *menuview; //菜单页
    UITableView *meutableview;
    UITableView *maintableview;
    
    NSMutableArray *nameAry;  //名字数组
    NSMutableArray *dataAry; //数据数组
    
    NSString *flag; //点击了第几行
    NSString *_id; //点击的id
    BOOL click; // 是否点击
    NSInteger witchclic;
}
@property(nonatomic,strong)NSMutableArray *openarray;
@property(nonatomic,strong)objmodel *model;
@end

@implementation ShoppingMainVC
-(NSMutableArray *)openarray
{
    if (!_openarray) {
        _openarray=[NSMutableArray array];
    }
    return _openarray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    flag = @"100";
    nameAry = [[NSMutableArray alloc]init];
    dataAry = [[NSMutableArray alloc]init];
    [self loadmenuView];
    [self loadNav];
    [self loadNamedata];
    // Do any additional setup after loading the view.
}
-(void)loadNamedata{
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    
    [MyMbd addHudToView:self.view];
    [WXDataService requestWithURL:@"mobile/commodity/listCommodityCategory.jhtml" params:params httpMethod:@"POST" block:^(id result, NSString *success, NSString *msg) {
        [MyMbd hidenHudFromView:self.view];
        BOOL suc =[success boolValue];
        if (suc == 0 ) {
            UIAlertView *deleAlertView=[[UIAlertView alloc]initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [deleAlertView show];
            return;
        }else if(suc == 1){
            nameAry = result[@"commodity_categories"][@"listItems"];
            for (NSInteger i =0; i<nameAry.count; i++) {
                objmodel *model = [[objmodel alloc]init];
                [self.openarray addObject:model];
            }
            [self loadmainView];
        }
    }failblock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MyMbd hidenHudFromView:self.view];
    }];
}
#pragma mark - data
-(void)loaddatawith:(NSString *)id_{
    
    [MyMbd addHudToView:self.view];
    

    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:@"1" forKey:@"page"];
    [params setObject:id_ forKey:@"commodity_category_id_"];
    [params setObject:@"-1" forKey:@"name"];
    [params setObject:@"2" forKey:@"flag"];
    [WXDataService requestWithURL:@"mobile/commodity/listCommodityPage.jhtml" params:params httpMethod:@"POST" block:^(id result, NSString *success, NSString *msg) {
        
        [MyMbd hidenHudFromView:self.view];
        
        NSLog(@"%@",result);
        
        BOOL suc =[success boolValue];
        if (suc == 0 ) {
            UIAlertView *deleAlertView=[[UIAlertView alloc]initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [deleAlertView show];
            return;
        }else if(suc == 1){
            
            
            NSLog(@"ranggekankan request---=-=-=%@",result);
            
            dataAry = result[@"commodities"][@"listItems"];
            [maintableview reloadData];
            
            
        }
    }failblock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MyMbd hidenHudFromView:self.view];

    }];
}
-(void)change
{
    

}

#pragma mark - mainview
-(void)loadmainView{
    maintableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 60, ScreenW, ScreenH)];
    maintableview.delegate = self;
    maintableview.dataSource = self;
    maintableview.tableFooterView = [[UITableView alloc]init];
    maintableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [mainView addSubview:maintableview];
}
#pragma mark - nav
-(void)loadNav{
    mainView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH)];
    mainView.backgroundColor = DRINK_LIGHTGRAY_COLOR;
    [self.view addSubview:mainView];
    UIView *redview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 20)];
    redview.backgroundColor = DRINK_RED_COLOR;
    [mainView addSubview:redview];
    
    UILabel *redLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, ScreenW, 40)];
    redLab.backgroundColor = DRINK_RED_COLOR;
    redLab.text = @"商城";
    redLab.textColor = [UIColor whiteColor];
    redLab.textAlignment =  NSTextAlignmentCenter;
    redLab.font = [UIFont boldSystemFontOfSize:17];
    [mainView addSubview:redLab];
    
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 20,44, 40)];
    backBtn.adjustsImageWhenHighlighted = NO;
    [backBtn setBackgroundImage:[UIImage imageNamed:@"菜单"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(clickBack:) forControlEvents:UIControlEventTouchUpInside];
    [mainView addSubview:backBtn];
}
#pragma mark - 菜单页
-(void)loadmenuView{
    menuview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW *0.75, ScreenH)];
    menuview.backgroundColor = DRINK_LIGHTGRAY_COLOR;
    for(int i=1;i<9;i++){
        NSArray *menuAry = @[@"    首页",@"    商城",@"    订单",@"    余额",@"    库存",@"    申请返利",@"    关于我们",@"    退出"];
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 100+41*i, ScreenW *0.75, 40)];
        btn.tag = i;
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        btn.backgroundColor = [UIColor whiteColor];
        [btn setTitle:[menuAry objectAtIndex:i-1] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(clickmenu:) forControlEvents:UIControlEventTouchUpInside];
        [menuview addSubview:btn];
    }
    //上面头像等
    UIImageView*imageview = [[UIImageView alloc]init];
    imageview.backgroundColor = [UIColor whiteColor];
    NSString *string =  [NSString stringWithFormat:@"%@%@",BASE_URL,USER_IMG];
    NSURL *imgurl = [NSURL URLWithString:string];

    [imageview setImageWithURL:imgurl placeholderImage:[UIImage imageNamed:@"代理商信息头像_150.png"]];
    imageview.frame =CGRectMake(20, 40, 80, 80);
    imageview.layer.masksToBounds = YES;
    imageview.layer.cornerRadius = 5;
    imageview.userInteractionEnabled = YES;
//    //单击手势
    UITapGestureRecognizer *sigleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(signalTapAction)];
    [imageview addGestureRecognizer:sigleTap];
    [menuview addSubview:imageview];
    
    //名称
    UILabel *nameLab = [[UILabel alloc]initWithFrame:CGRectMake(120, 40, ScreenW *0.75 - 120, 20)];
    nameLab.text = CPOMANY_NAME;
    nameLab.font = [UIFont systemFontOfSize:15];
    [menuview addSubview:nameLab];
    //等级
    UILabel *levelLab = [[UILabel alloc]initWithFrame:CGRectMake(120, 65, ScreenW *0.75 - 120, 20)];
    levelLab.font = [UIFont systemFontOfSize:15];
    switch ([USER_LEVEL integerValue]) {
        case 1:
            levelLab.text =@"省级代理";
            break;
        case 2:
            levelLab.text =@"市级代理";
            break;
        case 3:
            levelLab.text =@"县级代理";
            break;
        case 4:
            levelLab.text =@"采集代理";
            break;
            
        default:
            break;
    }
    [menuview addSubview:levelLab];
    
    //中间竖线
    UIView *vieww = [[UIView alloc]initWithFrame:CGRectMake(ScreenW *0.75-1, 0, 1, ScreenH)];
    vieww.backgroundColor = [UIColor blackColor];
    vieww.layer.shadowColor = [[UIColor blackColor]CGColor];
    vieww.layer.shadowRadius = 3;
    vieww.layer.shadowOpacity = 0.9;
    vieww.layer.shadowOffset = CGSizeMake(-3, 0);
    [menuview addSubview:vieww];
    [self.view addSubview:menuview];
}
#pragma mark - 点击菜单
-(void)clickmenu:(UIButton *)sender{
//    switch (sender.tag - 1) {
    
//NSArray *subControllers = @[@"",@"",@"CollectionViewController",@"ConfidelistViewController",@"",@"",@""];
    NSArray *array = @[@"HeadVC",@"ShoppingMainVC",@"OrderMainVC",@"BalanceVC",@"StockVC",@"ApplyVC",@"AboutOurVC",@"LandingVC"];
    if (sender.tag<9) {
        NSDictionary *dic = [NSDictionary dictionary];
        dic = @{@"vc":array[sender.tag-1]};
        
        NSLog(@"%@",dic);
        
        if ( sender.tag-1==0) {
            [self dismissViewControllerAnimated:NO completion:^{}];
            
        }else
        {
            if (sender.tag == 8) {
                [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"tuichudenglu"];
            }
            [self dismissViewControllerAnimated:NO completion:^{}];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"ceshi" object:self userInfo:dic];
            
            
        }
    }else
    {
        AppDelegate *dele = (AppDelegate *)[[UIApplication sharedApplication]delegate] ;
        NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
        [userDefaultes setObject: nil forKey:@"USER_ID"];
        [userDefaultes setObject:nil forKey:@"USER_PWD"];
        [userDefaultes setObject:nil forKey:@"USER_IMG"];
        [userDefaultes setObject:nil forKey:@"USER_LEVEL"];
        [userDefaultes setObject:nil forKey:@"USER_ACCOUNT"];
        [userDefaultes setObject:nil forKey:@"USER_DIC"];
        [userDefaultes setObject:nil forKey:@"CPOMANY_NAME"];
        [userDefaultes synchronize];
        [dele showMain];
    }
}

-(void)viewTapAction{
    [maintableview removeGestureRecognizer:self.tap];
    [UIView animateWithDuration:0.2 animations:^(){
        mainView.frame = CGRectMake(0, 0, ScreenW, ScreenH);
    }];
}

#pragma mark - 菜单按钮
-(void)clickBack:(UIButton *)sender{
    sender.selected = !sender.selected;
    
    if(sender.selected){
        [UIView animateWithDuration:0.2 animations:^(){
            mainView.frame = CGRectMake(ScreenW*0.75, 0, ScreenW, ScreenH);
            sender.selected = NO;
        }];
        
        UIView *shoushiView = [[UIView alloc]initWithFrame:CGRectMake(ScreenW*0.75, 0, ScreenW*0.25, ScreenH)];
        
        shoushiView.tag = 1999;
        shoushiView.userInteractionEnabled = YES;
        shoushiView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:shoushiView];
        //单击手势
        UITapGestureRecognizer *sigleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewTapAction)];
        
        self.tap = sigleTap;
        //设置点击手指的根数
        sigleTap.numberOfTouchesRequired = 1;
        //点击屏幕次数
        sigleTap.numberOfTapsRequired = 1;
        [shoushiView addGestureRecognizer:sigleTap];
    }else{
        UIView *view = (UIView *)[self.view viewWithTag:1999];
        [view removeFromSuperview];
        [UIView animateWithDuration:0.2 animations:^(){
            mainView.frame = CGRectMake(0, 0, ScreenW, ScreenH);
        }];
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView        {
    
    return nameAry.count;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
        ConcludeOrderVC *concluvc = [[ConcludeOrderVC alloc]init];
//        concluvc.modalPresentationStyle = UIModalTransitionStyleCoverVertical;
        concluvc.datadic =dataAry[indexPath.row];
        [self presentViewController:concluvc animated:YES completion:nil];
}
#pragma mark - 点击头像
-(void)signalTapAction{
    [self dismissViewControllerAnimated:NO completion:nil];
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@"AgentVC" forKey:@"vc"];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"ceshi" object:nil userInfo:dic];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark---自己重新写的
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    TypeBtn *butten = [[TypeBtn alloc]init ];
    butten.frame =CGRectMake(0, 0, 375, 40);
//    butten.model = model;
    butten.model = self.openarray[section];
    [butten addline:nameAry WithSection:section];
    [butten addTarget:self action:@selector(buttenClic:) forControlEvents:UIControlEventTouchUpInside];
    

    return butten;
//_id =[nameAry objectAtIndex:indexPath.section][@"id_"];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == self.buten.tag) {
        
//        if (dataAry.count==0) {
//            return 1;
//        }else
//        {
            return dataAry.count;

//        }
        
    }
    

    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ShopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (!cell) {
        cell = [[ShopTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.contentView.backgroundColor = DRINK_LIGHTGRAY_COLOR;
        
    }
    NSString *str=[NSString stringWithFormat:@"      %@",[dataAry objectAtIndex:indexPath.row][@"name"]];
    [cell changeName:str];
        return cell;

}
-(void)buttenClic:(TypeBtn *)butten
{
    objmodel *model=  self.openarray[self.buten.tag];
    model.isopen = NO;

    witchclic = butten.tag;
    butten.selected = !self.buten.selected;
    if (butten.selected) {
        _id =[nameAry objectAtIndex:butten.tag][@"id_"];
        [self loaddatawith:_id];
        objmodel *model=  self.openarray[butten.tag];
        model.isopen = YES;
        butten.hidden = NO;
        

    }else
    {
        butten.lable.hidden = YES;
        [dataAry removeAllObjects];
        [maintableview reloadData];

    }
    self.buten = butten;
    
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//
//    return 100;
//}

@end
